<template>
    <div class="min-h-screen bg-gray-50">
        <!-- Navigation Header -->
        
    <header class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            <div class="flex-shrink-0 flex items-center">
              <h1 class="text-2xl font-bold text-primary">MyBank</h1>
            </div>
            <nav class="hidden sm:ml-6 sm:flex sm:space-x-8">
              <router-link to="/dashboard" class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
                :class="{
                  'border-primary text-gray-900': $route.name === 'Dashboard',
                  'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700': $route.name !== 'Dashboard'
                }">
                首页
              </router-link>
              <router-link to="/accounts" class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
                :class="{
                  'border-primary text-gray-900': $route.name === 'Accounts',
                  'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700': $route.name !== 'Accounts'
                }">
                账户
              </router-link>
              <router-link to="/cards" class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
                :class="{
                  'border-primary text-gray-900': $route.name === 'Cards',
                  'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700': $route.name !== 'Cards'
                }">
                卡片
              </router-link>
              <router-link to="/loans" class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
                :class="{
                  'border-primary text-gray-900': $route.name === 'Loans',
                  'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700': $route.name !== 'Loans'
                }">
                贷款
              </router-link>
              <router-link to="/settings" class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
                :class="{
                  'border-primary text-gray-900': $route.name === 'settings',
                  'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700': $route.name !== 'settings'
                }">
                设置
              </router-link>
            </nav>
          </div>
          <div class="flex items-center">
            <button
              class="p-1 rounded-full text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
              <span class="sr-only">View notifications</span>
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
              </svg>
            </button>
            <div class="ml-3 relative">
              <div>
                <button
                  class="bg-white rounded-full flex text-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                  <span class="sr-only">Open user menu</span>
                  <div class="h-8 w-8 rounded-full bg-primary text-white flex items-center justify-center">
                    {{ username }}
                  </div>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </header>
    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">

              <!-- Page Header -->
      <div class="px-4 sm:px-0 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h2 class="text-2xl font-semibold text-gray-900">账户管理</h2>
            <p class="mt-1 text-sm text-gray-600">查询和管理你的各种账户。</p>
          </div>
          <div class="mt-4 sm:mt-0">
            <button 
              @click="navigateToAccountApplication" 
              class="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-md text-sm font-medium"
            >
              申请新账户
            </button>
          </div>
        </div>
      </div>
      <div class="overview-header">
 
        <div class="quick-actions">
          <button class="action-button" @click="navigateTo('transaction-simulator')">
            <span class="action-icon">↗</span>
            <span>转账</span>
          </button>
          <button class="action-button" @click="navigateTo('transaction-simulator')">
            <span class="action-icon">💰</span>
            <span>付账单</span>
          </button>
          <button class="action-button" @click="navigateTo('transaction-simulator')">
            <span class="action-icon">📱</span>
            <span>存钱</span>
          </button>
          <button class="action-button" @click="navigateTo('bank-statements')">
            <span class="action-icon">📄</span>
            <span>银行声明</span>
          </button>
        </div>
      </div>
  
      <!-- Financial Summary -->
      <div class="financial-summary">
        <div class="summary-card total-assets">
          <h3>总余额</h3>
          <div v-if="isLoadingTotalBalance" class="amount">加载中...</div>
          <div v-else-if="totalBalanceError" class="amount error-text">
            <span title="点击重试" @click="fetchTotalBalance">获取失败</span>
          </div>
          <div v-else class="amount">${{ formatCurrency(totalBalance) }}</div>
        </div>
      </div>
  
      <!-- Accounts Section -->
      <div class="accounts-section">
        <h2>账户总览</h2>
        
        <!-- Loading state -->
        <div v-if="isLoading" class="bg-white p-6 rounded-lg shadow text-center" style="width: 100%;">
          <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-primary mx-auto mb-4"></div>
          <p class="text-gray-600">加载账户信息中...</p>
        </div>
        
        <!-- Error state -->
        <div v-else-if="error" class="bg-white p-6 rounded-lg shadow" style="width: 100%;">
          <div class="text-red-500 mb-2">{{ error }}</div>
          <button @click="fetchAccountData" class="text-primary hover:text-primary-dark">
            重试
          </button>
        </div>
        
        <!-- Accounts grid -->
        <div v-else class="grid grid-cols-1 gap-5 sm:grid-cols-2" style="width: 100%; max-width: 100%;">
          <div v-for="account in accounts" :key="account.id" class="bg-white overflow-hidden shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <div class="flex items-center">
                <div class="flex-shrink-0 rounded-md p-3" :class="getAccountIconClass(account.type)">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                      d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                  </svg>
                </div>
                <div class="ml-5 w-0 flex-1">
                  <dl>
                    <dt class="text-sm font-medium text-gray-500 truncate">
                      {{ account.name }}
                    </dt>
                    <dd class="text-xs text-gray-500 mb-1">
                      {{ account.number }}
                    </dd>
                    <dd>
                      <div class="text-lg font-medium text-gray-900">
                        {{ formatCurrency(account.balance) }}
                      </div>
                    </dd>
                  </dl>
                </div>
              </div>
            </div>
            <div class="bg-gray-50 px-4 py-4 sm:px-6">
              <div class="text-sm">
                <router-link :to="`/accounts/${account.id}`" class="font-medium text-primary hover:text-primary-dark">
                  详细信息点这里
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- Recent Transactions -->
      <div class="recent-transactions">
        <div class="section-header">
          <h2>近期交易一览</h2>
          <button class="view-all-button" @click="navigateTo('transactions')">查询更多</button>
        </div>
        
        <!-- Loading state -->
        <div v-if="isLoadingTransactions" class="bg-white p-6 rounded-lg shadow text-center" style="width: 100%;">
          <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-primary mx-auto mb-4"></div>
          <p class="text-gray-600">加载交易信息中...</p>
        </div>
        
        <!-- Error state -->
        <div v-else-if="transactionError" class="bg-white p-6 rounded-lg shadow" style="width: 100%;">
          <div class="text-red-500 mb-2">{{ transactionError }}</div>
          <button @click="fetchRecentTransactions" class="text-primary hover:text-primary-dark">
            重试
          </button>
        </div>
        
        <!-- Transactions list -->
        <div v-else class="bg-white shadow overflow-hidden sm:rounded-md">
          <ul class="divide-y divide-gray-200">
            <li v-for="transaction in recentTransactions.slice(0, 5)" :key="transaction.transactionId" class="px-4 py-4 sm:px-6">
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <div class="flex-shrink-0 rounded-md p-2" :class="getTransactionIconClass(transaction.transactionType, transaction.amount)">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="getTransactionIcon(transaction.transactionType)" />
                    </svg>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">
                      {{ transaction.description || getTransactionTypeLabel(transaction.transactionType) }}
                    </div>
                    <div class="text-sm text-gray-500">
                      {{ formatDate(transaction.transactionDate) }}
                    </div>
                  </div>
                </div>
                <div class="text-sm" :class="transaction.amount < 0 ? 'text-red-600' : 'text-green-600'">
                  {{ transaction.amount < 0 ? '-' : '+' }}{{ formatCurrency(Math.abs(transaction.amount)) }}
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      
 
    
    </main>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import authService from '../services/authService';
  import accountService from '../services/accountService';

  const router = useRouter();
  const username = ref('');

  // Account data
  const accounts = ref([]);
  const isLoading = ref(true);
  const error = ref(null);

  // Transaction data
  const recentTransactions = ref([]);
  const isLoadingTransactions = ref(true);
  const transactionError = ref(null);

  // Total balance data
  const isLoadingTotalBalance = ref(false);
  const totalBalanceError = ref(null);
  const totalBalance = ref(0);

  const getUserFromToken = () => {
    const token = localStorage.getItem('token')
    if (!token) return null
    
    try {
      const tokenParts = token.split('.')
      if (tokenParts.length === 3) {
        const payload = JSON.parse(atob(tokenParts[1]))
        return {
          firstName: payload.firstName || '',
          lastName: payload.lastName || ''
        }
      }
    } catch (error) {
      console.error('Error extracting user data from token:', error)
    }
    return null
  }

  const checkAuthStatus = () => {
    if (authService.isAuthenticated()) {
      // Try to get from localStorage first
      let user = JSON.parse(localStorage.getItem('user') || '{}')
      
      // If firstName or lastName is missing, extract from token
      if (!user.firstName || !user.lastName) {
        const tokenUser = getUserFromToken()
        if (tokenUser) {
          // Merge token data with existing user data
          user = { ...user, ...tokenUser }
          // Update localStorage with complete user data
          localStorage.setItem('user', JSON.stringify(user))
        }
      }
      
      // Set the full name (last name + first name)
      username.value = user.lastName && user.firstName 
        ? `${user.lastName} ${user.firstName}`
        : user.lastName || user.firstName || ''
    } else {
      username.value = ''
    }
  }

  // Extract user ID from token
  const getUserIdFromToken = () => {
    const token = localStorage.getItem('token');
    if (!token) return null;
    
    try {
      const tokenParts = token.split('.');
      if (tokenParts.length === 3) {
        const payload = JSON.parse(atob(tokenParts[1]));
        
        // Extract just the numeric ID from the sub field
        let userId = payload.sub || payload.id || '';
        
        // If the ID contains a comma, extract just the number part
        if (typeof userId === 'string' && userId.includes(',')) {
          userId = userId.split(',')[0].trim();
        }
        
        return userId;
      }
    } catch (error) {
      console.error('Error extracting user ID from token:', error);
    }
    return null;
  };

  // Function to fetch total balance
  const fetchTotalBalance = async () => {
    isLoadingTotalBalance.value = true;
    totalBalanceError.value = null;
    
    try {
      const userId = getUserIdFromToken();
      if (!userId) {
        throw new Error('无法获取用户ID');
      }
      
      console.log('Fetching total balance for user ID:', userId);
      const response = await accountService.getUserTotalBalance(userId);
      console.log(response)
      // Check if response has totalBalance property and it's a number
      if (response && typeof response === 'number') {
        totalBalance.value = response;
      } else {
        console.warn('Invalid total balance response:', response);
        // Set to 0 if invalid response
        totalBalance.value = 0;
      }
      
      console.log('Fetched total balance:', totalBalance.value);
    } catch (err) {
      console.error('Error fetching total balance:', err);
      totalBalanceError.value = '获取总余额失败，请稍后再试';
      
      // Keep using 0 as fallback
      totalBalance.value = 0;
    } finally {
      isLoadingTotalBalance.value = false;
    }
  };

  // Function to fetch account data
  const fetchAccountData = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const userId = getUserIdFromToken();
      if (!userId) {
        throw new Error('无法获取用户ID');
      }
      
      console.log('Fetching accounts for user ID:', userId);
      const response = await accountService.getUserAccountBalances(userId);
      
      // Check if response has data property or is the data itself
      const accountsData = response.data || response;
      
      if (!Array.isArray(accountsData)) {
        console.error('Unexpected response format:', accountsData);
        throw new Error('服务器返回的数据格式不正确');
      }
      
      // Process and store the account data
      accounts.value = accountsData.map(account => ({
        id: account.accountId,
        name: account.accountName || '账户',
        number: account.accountNumber,
        type: account.accountType || '储蓄账户',
        balance: account.balance || 0
      }));
      
      console.log('Fetched accounts:', accounts.value);
    } catch (err) {
      console.error('Error fetching account data:', err);
      error.value = '获取账户数据失败，请稍后再试';
      
      // Fallback to empty accounts array
      accounts.value = [];
    } finally {
      isLoading.value = false;
    }
  };

  // Function to fetch recent transactions
  const fetchRecentTransactions = async () => {
    isLoadingTransactions.value = true;
    transactionError.value = null;
    
    try {
      const userId = getUserIdFromToken();
      if (!userId) {
        throw new Error('无法获取用户ID');
      }
      
      console.log('Fetching recent transactions for user ID:', userId);
      const token = authService.getToken();
      
      const response = await fetch(`http://localhost:8080/api/accounts/user/${userId}/recent-transactions`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      console.log('Fetched recent transactions:', data);
      
      // Process and store the transaction data
      recentTransactions.value = Array.isArray(data) ? data : [];
    } catch (err) {
      console.error('Error fetching recent transactions:', err);
      transactionError.value = '获取交易数据失败，请稍后再试';
      
      // Fallback to empty transactions array
      recentTransactions.value = [];
    } finally {
      isLoadingTransactions.value = false;
    }
  };

  // Helper functions for account and transaction display
  const getAccountIconClass = (accountType) => {
    const type = (accountType || '').toLowerCase();
    if (type.includes('saving') || type.includes('储蓄')) {
      return 'bg-blue-100 text-blue-600';
    } else if (type.includes('check') || type.includes('支票')) {
      return 'bg-green-100 text-green-600';
    } else if (type.includes('credit') || type.includes('信用')) {
      return 'bg-purple-100 text-purple-600';
    } else if (type.includes('loan') || type.includes('贷款')) {
      return 'bg-red-100 text-red-600';
    } else {
      return 'bg-gray-100 text-gray-600';
    }
  };

  const getTransactionIconClass = (type, amount) => {
    const transactionType = (type || '').toLowerCase();
    
    if (amount < 0) {
      return 'bg-red-100 text-red-600';
    } else if (transactionType.includes('deposit') || transactionType.includes('存款')) {
      return 'bg-green-100 text-green-600';
    } else if (transactionType.includes('transfer') || transactionType.includes('转账')) {
      return 'bg-blue-100 text-blue-600';
    } else {
      return 'bg-gray-100 text-gray-600';
    }
  };

  const getTransactionIcon = (type) => {
    const transactionType = (type || '').toLowerCase();
    
    if (transactionType.includes('withdraw') || transactionType.includes('取款')) {
      return 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z';
    } else if (transactionType.includes('deposit') || transactionType.includes('存款')) {
      return 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z';
    } else if (transactionType.includes('transfer') || transactionType.includes('转账')) {
      return 'M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4';
    } else {
      return 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2';
    }
  };

  const getTransactionTypeLabel = (type) => {
    const transactionType = (type || '').toLowerCase();
    
    if (transactionType.includes('withdraw') || transactionType.includes('取款')) {
      return '取款';
    } else if (transactionType.includes('deposit') || transactionType.includes('存款')) {
      return '存款';
    } else if (transactionType.includes('transfer') || transactionType.includes('转账')) {
      return '转账';
    } else if (transactionType.includes('payment') || transactionType.includes('付款')) {
      return '付款';
    } else {
      return '交易';
    }
  };

  // Helper functions
  const formatCurrency = (value) => {
    // Handle undefined, null, or non-numeric values
    if (value === undefined || value === null || isNaN(value)) {
      return '0.00';
    }
    return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  };

  const formatDate = (date) => {
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const formatShortDate = (date) => {
    return new Date(date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric'
    });
  };

  // Action functions
  const navigateTo = (route, id) => {
    console.log(`Navigating to ${route}${id ? ' with ID: ' + id : ''}`);
    if (id) {
      router.push({ name: route, params: { accountId: id } });
    } else {
      router.push({ name: route });
    }
  };

  const viewAccountDetails = (accountId) => {
    console.log(`Viewing account details for: ${accountId}`);
    // In a real app, this would navigate to the account details page
    // router.push({ name: 'account-details', params: { id: accountId } });
  };

  const navigateToAccountApplication = () => {
    router.push('/account-application');
  };

  onMounted(() => {
    checkAuthStatus();
    
    // Fetch total balance
    fetchTotalBalance();
    
    // Fetch account data
    fetchAccountData();
    
    // Fetch recent transactions
    fetchRecentTransactions();
    
    // Listen for auth state changes
    window.addEventListener('auth-state-changed', checkAuthStatus);
    
    // Add event listener for storage changes to handle login/logout in other tabs
    window.addEventListener('storage', (event) => {
      if (event.key === 'token' || event.key === 'user') {
        checkAuthStatus();
        fetchTotalBalance();
        fetchAccountData();
        fetchRecentTransactions();
      }
    });
  });

  onUnmounted(() => {
    window.removeEventListener('auth-state-changed', checkAuthStatus);
    window.removeEventListener('storage', checkAuthStatus);
  });
  </script>
  
  <style scoped>
  .account-overview {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 1rem 2rem;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    color: #333;
  }
  
  .overview-header {
    background-color: #1e40af;
    color: white;
    padding: 2rem;
    border-radius: 0.5rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }
  
  .welcome-section {
    margin-bottom: 1.5rem;
  }
  
  .welcome-section h1 {
    font-size: 1.75rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
  }
  
  .last-login {
    font-size: 0.875rem;
    opacity: 0.9;
  }
  
  .quick-actions {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
  }
  
  .action-button {
    background-color: rgba(255, 255, 255, 0.2);
    border: none;
    border-radius: 0.5rem;
    padding: 0.75rem 1rem;
    color: white;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    transition: background-color 0.2s;
  }
  
  .action-button:hover {
    background-color: rgba(255, 255, 255, 0.3);
  }
  
  .action-icon {
    font-size: 1.25rem;
  }
  
  /* Financial Summary */
  .financial-summary {
    margin-bottom: 2rem;
  }
  
  .summary-card {
    background-color: white;
    border-radius: 0.5rem;
    padding: 1.5rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }
  
  .summary-card h3 {
    font-size: 1rem;
    font-weight: 500;
    color: #555;
    margin-bottom: 0.5rem;
  }
  
  .summary-card .amount {
    font-size: 1.75rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
  }
  
  .total-assets {
    border-top: 4px solid #4caf50;
  }
  
  /* Accounts Section */
  .accounts-section {
    margin-bottom: 2rem;
  }
  
  .accounts-section h2,
  .recent-transactions h2 {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: #333;
  }
  
  .accounts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 1rem;
  }
  
  .account-card {
    background-color: white;
    border-radius: 0.5rem;
    padding: 1.5rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
  }
  
  .account-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }
  
  .account-info {
    margin-bottom: 1rem;
  }
  
  .account-name {
    font-size: 1.125rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
  }
  
  .account-number {
    font-size: 0.875rem;
    color: #777;
  }
  
  .account-balance {
    margin-bottom: 1rem;
  }
  
  .balance-amount {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
  }
  
  .available {
    font-size: 0.875rem;
    color: #555;
  }
  
  .account-actions {
    display: flex;
    gap: 1rem;
    border-top: 1px solid #eee;
    padding-top: 1rem;
  }
  
  .action-link {
    background: none;
    border: none;
    color: #1e40af;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    padding: 0;
  }
  
  .action-link:hover {
    text-decoration: underline;
  }
  
  /* Recent Transactions */
  .recent-transactions {
    margin-bottom: 2rem;
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }
  
  .view-all-button {
    background: none;
    border: none;
    color: #1e40af;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
  }
  
  .view-all-button:hover {
    text-decoration: underline;
  }
  
  .transactions-list {
    background-color: white;
    border-radius: 0.5rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  .transaction-item {
    display: grid;
    grid-template-columns: 80px 1fr 120px 120px;
    padding: 1rem;
    border-bottom: 1px solid #eee;
  }
  
  .transaction-item:last-child {
    border-bottom: none;
  }
  
  .transaction-date {
    color: #777;
    font-size: 0.875rem;
  }
  
  .transaction-merchant {
    font-weight: 500;
  }
  
  .transaction-account {
    font-size: 0.875rem;
    color: #777;
  }
  
  .transaction-category {
    color: #555;
    font-size: 0.875rem;
  }
  
  .transaction-amount {
    font-weight: 600;
    text-align: right;
  }
  
  .transaction-amount.negative {
    color: #f44336;
  }
  
  /* Add Account Section */
  .add-account-section {
    margin-top: 2rem;
    text-align: center;
  }
  
  .add-account-button {
    background-color: white;
    border: 1px dashed #1e40af;
    border-radius: 0.5rem;
    padding: 1rem;
    color: #1e40af;
    font-weight: 500;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: background-color 0.2s;
  }
  
  .add-account-button:hover {
    background-color: #f0f7ff;
  }
  
  .add-icon {
    font-size: 1.25rem;
  }
  
  /* Responsive adjustments */
  @media (max-width: 768px) {
    .accounts-grid {
      grid-template-columns: 1fr;
    }
    
    .transaction-item {
      grid-template-columns: 80px 1fr 100px;
    }
    
    .transaction-category {
      display: none;
    }
  }
  
  @media (max-width: 480px) {
    .quick-actions {
      flex-direction: column;
    }
    
    .action-button {
      width: 100%;
    }
  }
  .error-text {
    color: #ef4444;
    cursor: pointer;
  }
  .error-text:hover {
    text-decoration: underline;
  }
  /* Add these styles for the accounts section */
  .accounts-section {
    margin-bottom: 2rem;
  }

  .accounts-section h2 {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: #1f2937;
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(1, minmax(0, 1fr));
    gap: 1.25rem;
  }

  @media (min-width: 640px) {
    .grid {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }

  .bg-white {
    background-color: white;
  }

  .shadow {
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  }

  .rounded-lg {
    border-radius: 0.5rem;
  }

  .overflow-hidden {
    overflow: hidden;
  }

  .animate-spin {
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  /* Add these styles for the recent transactions section */
  .recent-transactions {
    margin-bottom: 2rem;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }

  .section-header h2 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
  }

  .view-all-button {
    font-size: 0.875rem;
    color: #2563eb;
    background: none;
    border: none;
    cursor: pointer;
  }

  .view-all-button:hover {
    text-decoration: underline;
  }

  .divide-y > * + * {
    border-top-width: 1px;
    border-top-style: solid;
    border-top-color: #e5e7eb;
  }

  .text-red-600 {
    color: #dc2626;
  }

  .text-green-600 {
    color: #16a34a;
  }

  .bg-red-100 {
    background-color: #fee2e2;
  }

  .bg-green-100 {
    background-color: #dcfce7;
  }

  .bg-blue-100 {
    background-color: #dbeafe;
  }

  .bg-purple-100 {
    background-color: #f3e8ff;
  }

  .bg-gray-100 {
    background-color: #f3f4f6;
  }

  .text-red-600 {
    color: #dc2626;
  }

  .text-green-600 {
    color: #16a34a;
  }

  .text-blue-600 {
    color: #2563eb;
  }

  .text-purple-600 {
    color: #9333ea;
  }

  .text-gray-600 {
    color: #4b5563;
  }

  .rounded-md {
    border-radius: 0.375rem;
  }

  .p-2 {
    padding: 0.5rem;
  }

  .p-3 {
    padding: 0.75rem;
  }

  .p-6 {
    padding: 1.5rem;
  }

  .px-4 {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .py-4 {
    padding-top: 1rem;
    padding-bottom: 1rem;
  }

  .py-5 {
    padding-top: 1.25rem;
    padding-bottom: 1.25rem;
  }

  .sm\:p-6 {
    padding: 1.5rem;
  }

  .sm\:px-6 {
    padding-left: 1.5rem;
    padding-right: 1.5rem;
  }

  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .flex-shrink-0 {
    flex-shrink: 0;
  }

  .flex-1 {
    flex: 1 1 0%;
  }

  .ml-4 {
    margin-left: 1rem;
  }

  .ml-5 {
    margin-left: 1.25rem;
  }

  .mb-2 {
    margin-bottom: 0.5rem;
  }

  .mb-4 {
    margin-bottom: 1rem;
  }

  .w-0 {
    width: 0;
  }

  .h-5 {
    height: 1.25rem;
  }

  .w-5 {
    width: 1.25rem;
  }

  .h-6 {
    height: 1.5rem;
  }

  .w-6 {
    width: 1.5rem;
  }

  .h-10 {
    height: 2.5rem;
  }

  .w-10 {
    width: 2.5rem;
  }

  .text-sm {
    font-size: 0.875rem;
  }

  .text-xs {
    font-size: 0.75rem;
  }

  .text-lg {
    font-size: 1.125rem;
  }

  .font-medium {
    font-weight: 500;
  }

  .text-gray-500 {
    color: #6b7280;
  }

  .text-gray-900 {
    color: #111827;
  }

  .truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .border-b-2 {
    border-bottom-width: 2px;
  }

  .border-primary {
    border-color: #2563eb;
  }

  .text-primary {
    color: #2563eb;
  }

  .hover\:text-primary-dark:hover {
    color: #1d4ed8;
  }

  .bg-gray-50 {
    background-color: #f9fafb;
  }

  .mx-auto {
    margin-left: auto;
    margin-right: auto;
  }

  .text-center {
    text-align: center;
  }
  </style>
